var util = require('../../utils/util.js');
const {
  $Message
} = require('../../dist/base/index');
var app = getApp();

Page({
  data: {
    addressList: [],
    defut: {},

    items: [],
    startX: 0, //开始坐标
    startY: 0,


  },


  getAddressList() {
    let that = this;
    wx.request({
      url: app.globalData.url + '/shs/api/receiveAddress/list?current=1&size=5',
      data: {
        current: "1", //请求第一页
        size: "5"
      },
      method: 'POST',
      header: {
        'Accept': 'application/json',
        'ACCESS-TOKEN': wx.getStorageSync('token')
      },

      success: function(res) {
        console.log(res.data)
        wx.hideLoading();
        if (res.data.code == '1') {
          var listSize = res.data.obj.records.length;
          console.log('listSize=' + listSize);
          var newData = that.data.addressList;
          newData = res.data.obj.records;
          var total1 = res.data.obj.total;
          var newList = {};
          //当长度小于10表示没有下页数据了
          if (listSize < 5) {
            newList.hasMore = false;
          } else {
            newList.hasMore = true;
          }
          newList = newData;
          console.log('newData=' + newData);
          that.setData({
            addressList: newList,
            total: total1
          });

          console.log('addressList=' + that.data.addressList);

          for (var i = 0; i < newList.length; i++) {
            if (newList[i].isDefault == 1) {
              console.log(newList[i])
              that.setData({
                defut: newList[i]
              })
            }
          }

          that.setData({
            startNum: 2
          })
        } else {
          // util.msg("错误", res.data.msg)
          console.log("网络通，数据不成功")
        }
      },
      fail: function(res) {
        wx.hideLoading();
        console.log(res.data)
        // util.msg("错误", "通讯失败")
      }

    })
  },

  ed: function(e) {
    let that = this;

    var Ids = e.currentTarget.id;
    console.log("Ids=" + Ids)

    var list = that.data.addressList;
    var id = 0;
    for (var i = 0; i < list.length; i++) {
      if (list[i].isDefault == 1) {
        id = list[i].id;
        console.log("id=" + id)
      }
    }

    wx.request({
      url: app.globalData.url + '/shs/api/receiveAddress/updateById',
      data: {
        id: id, 
        isDefault: 0
      },
      method: 'POST',
      header: {
        'Accept': 'application/json',
        'ACCESS-TOKEN': wx.getStorageSync('token')
      },

      success: function(res) {
        console.log(res.data)
        if (res.data.code == '1') {
          wx.request({
            url: app.globalData.url + '/shs/api/receiveAddress/updateById',
            data: {
              id: Ids, 
              isDefault: 1
            },
            method: 'POST',
            header: {
              'Accept': 'application/json',
              'ACCESS-TOKEN': wx.getStorageSync('token')
            },

            success: function(res) {
              console.log(res.data)
              wx.hideLoading();
              if (res.data.code == '1') {
                wx.showToast({
                  title: '修改成功！',
                  icon: 'success',
                  duration: 2000
                })
                that.onShow();
              } else {
                console.log("网络通，数据不成功")
              }
            },
            fail: function(res) {
              wx.hideLoading();
              console.log(res.data)
            }

          })
        } else {
          console.log("网络通，数据不成功")
        }
      },
      fail: function(res) {
        wx.hideLoading();
        console.log(res.data)
        // util.msg("错误", "通讯失败")
      }

    })
  },

  // addressAddOrUpdate(event) {
  //   console.log(event)
  //   wx.navigateTo({
  //     url: '/pages/ucenter/addressAdd/addressAdd?id=' + event.currentTarget.dataset.addressId
  //   })
  // },

  deleteAddress(event) {
    console.log(event.target)
    let that = this;
    wx.showModal({
      title: '',
      content: '确定要删除地址？',
      success: function(res) {
        if (res.confirm) {
          let addressId = event.target.dataset.addressId;
          util.request(api.AddressDelete, {
            id: addressId
          }, 'POST').then(function(res) {
            if (res.errno === 0) {
              that.getAddressList();
            }
          });
          console.log('用户点击确定')
        }
      }
    })
    return false;

  },
  onLoad: function(options) {
    // 页面初始化 options为页面跳转所带来的参数

    var that = this;
    for (var i = 0; i < 10; i++) {
      this.data.items.push({
        content: i + " 向左滑动删除哦,向左滑动删除哦,向左滑动删除哦,向左滑动删除哦,向左滑动删除哦",
        isTouchMove: false //默认隐藏删除
      })
    }
    this.setData({
      items: this.data.items
    });
  },

  //手指触摸动作开始 记录起点X坐标
  touchstart: function(e) {
    //开始触摸时 重置所有删除
    this.data.addressList.forEach(function(v, i) {
      if (v.isTouchMove) //只操作为true的
        v.isTouchMove = false;
    })
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      addressList: this.data.addressList
    })
  },

  //滑动事件处理
  touchmove: function(e) {
    var that = this,
      index = e.currentTarget.dataset.index, //当前索引
      startX = that.data.startX, //开始X坐标
      startY = that.data.startY, //开始Y坐标
      touchMoveX = e.changedTouches[0].clientX, //滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY, //滑动变化坐标
      //获取滑动角度
      angle = that.angle({
        X: startX,
        Y: startY
      }, {
        X: touchMoveX,
        Y: touchMoveY
      });
    that.data.addressList.forEach(function(v, i) {
      v.isTouchMove = false
      //滑动超过30度角 return
      if (Math.abs(angle) > 30) return;
      if (i == index) {
        if (touchMoveX > startX) //右滑
          v.isTouchMove = false
        else //左滑
          v.isTouchMove = true
      }
    })

    //更新数据
    that.setData({
      addressList: that.data.addressList
    })

  },

  /**
   * 计算滑动角度
   * @param {Object} start 起点坐标
   * @param {Object} end 终点坐标
   */

  angle: function(start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },

  //删除事件
  del: function(e) {
    this.data.addressList.splice(e.currentTarget.dataset.index, 1)
    this.setData({
      addressList: this.data.addressList
    })
  },


  onReady: function() {
    // 页面渲染完成
  },
  onShow: function() {
    // 页面显示
    this.getAddressList();



  },

  onHide: function() {
    // 页面隐藏
  },
  onUnload: function() {
    // 页面关闭
  }
})